/*
 * GTK VNC Widget
 *
 * Copyright (C) 2006  Anthony Liguori <anthony@codemonkey.ws>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.0 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA
 */

#include "config.h"

#include "coroutine.h"
#include <stdio.h>
#include <stdlib.h>

static GThread *main_thread;
static GHashTable* lac_hash;
static GMutex *lac_lock;

#if 0
#define CO_DEBUG(OP) fprintf(stderr, "%s %p %s %d\n", OP, g_thread_self(), __FUNCTION__, __LINE__)
#else
#define CO_DEBUG(OP)
#endif

static void coroutine_system_init(void)
{
	if (!g_thread_supported()) {
	        CO_DEBUG("INIT");
		g_thread_init(NULL);
	}

    main_thread = g_thread_self();
    lac_hash = g_hash_table_new(NULL, NULL);
    lac_lock = g_mutex_new();
}

static gpointer coroutine_thread(gpointer opaque)
{
    struct thread_data* data = opaque;

    g_mutex_lock(lac_lock);
    struct lock_and_cond* lac = malloc(sizeof(struct lock_and_cond));
    lac->run_cond = g_cond_new();
    lac->run_lock = g_mutex_new();
    lac->socket_cond = g_cond_new();
    lac->socket_lock = g_mutex_new();
    lac->condition_cond = g_cond_new();
    lac->condition_lock = g_mutex_new();
    lac->wait_id = lac->condition_id = 0;
    g_hash_table_insert(lac_hash, g_thread_self(), lac);
    g_mutex_unlock(lac_lock);

    data->entry(data->data);

    return NULL;
}

GThread* coroutine_init(thread_entry* entry, void* data, int channel_type)
{
    if (main_thread == NULL)
        coroutine_system_init();

    struct thread_data* tdata = malloc(sizeof(struct thread_data));
    tdata->entry = entry;
    tdata->data = data;
    return g_thread_new(g_strdup_printf("socket_th_%d", channel_type), coroutine_thread, tdata);
}

gboolean coroutine_is_main(GThread* thread)
{
    return (!main_thread || thread == main_thread);
}

struct lock_and_cond* coroutine_get_lac(GThread *thread)
{
    g_mutex_lock(lac_lock);
    struct lock_and_cond* lac = g_hash_table_lookup(lac_hash, thread);
    g_mutex_unlock(lac_lock);
    return lac;
}
